<template>
  <div class="app-container">

    <search-bar :form="queryParams" @sub="getList"></search-bar>

    <el-row :gutter="10">
      <el-col :span="1.5">
        <el-button @click="handleAdd">新增</el-button>
      </el-col>
      <right-toolbar @queryTable="Refresh"></right-toolbar>
    </el-row>

    <vxe-table ref="table" :loading="tableData.loading" :data="tableData.list" border>
      <vxe-column width="120" field="imgUrl" title="图片" align="center">
        <template #default="{ row }">
          <el-tooltip v-if="row.imgUrl" class="box-item" effect="dark" placement="right-start">
            <template #content>
              <img alt="" :src="showImg(row.imgUrl)" width="100" height="100" />
            </template>
            <img alt="" :src="showImg(row.imgUrl)" width="30" height="30" />
          </el-tooltip>
          <span v-else>没有图片</span>
        </template>
      </vxe-column>

      <vxe-column field="state" title="状态" width="80" align="center">
        <template #default="{ row }">
          <dict-tag :options="normal_cannot_status" :value="row.state" />
        </template>
      </vxe-column>

      <vxe-column field="number" title="编码" width="120" align="center" />
      <vxe-column field="name" title="名称" width="180" align="center" />
      <vxe-column field="categoryName" title="分类" width="120" align="center" />
      <vxe-column field="barcode" title="商品条码" width="120" align="center" />
      <vxe-column field="brand" title="品牌" width="120" align="center" />
      <vxe-column field="model" title="规格型号" width="120" align="center" />
      <vxe-column field="price" title="单价" width="120" align="center" />
      <vxe-column field="unit" title="计量单位" width="120" align="center" />

      <vxe-column field="useLimit" title="限领数量" width="120" align="center" />
      <vxe-column field="inventoryMax" title="安全库存上限" width="120" align="center" />
      <vxe-column field="inventoryMin" title="安全库存下限" width="120" align="center" />

      <vxe-column title="操作" fixed="right" width="150" align="center">
        <template #default="{ row }">
          <el-button size="small" link type="primary" @click="handleUpdate(row)">修改</el-button>
          <el-button size="small" link type="primary" @click="handleEnable(row)">启用</el-button>
          <el-button size="small" link type="primary" @click="handleDisable(row)">禁用</el-button>
          <el-button size="small" link type="primary" @click="handleDelete(row)">删除</el-button>
        </template>
      </vxe-column>
    </vxe-table>
    <div class="pagination-container">

      <pagination v-show="tableData.paging.total > 0" :total="tableData.paging.total"
        v-model:page="tableData.paging.pageNum" v-model:limit="tableData.paging.pageSize" @pagination="getList" />
    </div>

    <edit ref="editDialog" @sub="getList"></edit>

  </div>
</template>

<script setup>

import { listAssetItem, delAssetItem, exportAssetItem   } from "./api.js";
import Edit from './edit'
import SearchBar from "./SearchBar.vue";

const { proxy } = getCurrentInstance();
const { normal_cannot_status } = proxy.useDict("normal_cannot_status");



const editDialog = ref();
const loading = ref(false);
const table = ref();
const tableData = reactive({
  loading: false,
  list: [],
  paging: {
    total: 0,
    pageNum: 1,
    pageSize: 10,
  }
});

const initQueryParams = {
  state: null,
  field: 'number',
  value: null,
  pageNum: 1,
  pageSize: 10,
  number: null,
  name: null,
  categoryId: null,
  rfid: null,
  brand: null,
  model: null,
  buyWay: null,
  buyTime: null,
  buyPrice: null,
  adminId: null
}
const queryParams = reactive({ ...initQueryParams })

async function getList() {
  loading.value = true;
  const { pageNum, pageSize } = tableData.paging;
  const query = { ...queryParams };
  const pageReq = { page: pageNum - 1, size: pageSize };
  listAssetItem(query, pageReq).then(response => {
    const { content, totalElements } = response;
    tableData.list = content;
    tableData.paging.total = totalElements;
    tableData.loading = false;
  }).catch(error => {
    tableData.loading = false;
    console.error(error);
  });
}

function reset() {
  Object.assign(queryParams, initQueryParams);
}

function handleQuery() {
  tableData.paging.pageNum = 1;
  getList();
}

function resetQuery() {
  reset();
  handleQuery();
}

function showImg(img) {
  return import.meta.env.VITE_APP_BASE_API + img;
}

function handleAdd() {
  editDialog.value.open();
}

function handleUpdate(row) {
  editDialog.value.open(row);
}

async function handleEnable(row) {
  try {
    loading.value = true; 
    // await updateAssetState({ id: row.id, state: '正常' });
    proxy.$message.success(`资产 "${row.name}" 已启用`);
    getList();
  } catch (error) {
    proxy.$message.error('启用失败，请稍后重试');
    console.error(error);
  } finally {
    loading.value = false; 
  }
}

async function handleDisable(row) {
  try {
    loading.value = true; 
    // await updateAssetState({ id: row.id, state: '禁用' });
    proxy.$message.success(`资产 "${row.name}" 已禁用`);
    getList();
  } catch (error) {
    proxy.$message.error('禁用失败，请稍后重试');
    console.error(error);
  } finally {
    loading.value = false; 
  }
}

function handleDelete(row) {
  proxy.$modal.confirm(`是否确认删除资产清单表编号为"${row.id}"的数据项？`).then(() => {
    return delAssetItem(row.id);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
    proxy.$modal.msgError("删除失败");
  });
}

function Refresh() {
  getList();
  proxy.$message.success("刷新成功");
}

onMounted(() => {
  getList();
});
</script>

<style lang="scss" scoped>
.app-container {
  display: flex;
  flex-direction: column;
  height: 92vh;
  overflow: hidden;
}

.vxe-table {
  flex: 1;
  overflow: auto;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;

}

.box1 {
  height: 100px;
}
</style>
